import os
import re
import traceback

from app.conf import settings
from app.utils.custom_exc import CustomException
from app.utils.storage.minioClient import go_upload_file_have_size, go_delete_file, get_file_url
from app.utils.utils import get_now_time_string

default_Type_list = ['png', 'jpg', 'jpeg']

image_list = ['png', 'jpg', 'jpeg']
svg_list = ["svg"]

# ---------------------------------------- 本地保存 ------------------------------------------------------------------


def save_to_local_storage_file(file, folder='image', auth_file_type_list=None, auth_type=True, file_name=None, base_path=settings.BASE_DIR):
    try:
        f_type = str(file.filename).split('.')[-1]
        f_nem = str(file.filename)[:-len(f_type) - 1]
        file_type = auth_file_type_list if auth_file_type_list else default_Type_list
        if auth_type and str(f_type).lower() not in file_type:
            msg = f'不支持{f_type}, 仅支持{",".join(file_type)}格式'
            raise CustomException(err_desc=msg)

        if file_name is None:
            file_name = get_now_time_string()
        filepath = '{}/{}'.format(folder, file_name + '.' + f_type)

        exists_path = base_path + f'/{folder}'
        if not os.path.exists(exists_path): os.makedirs(exists_path)
        openfile = base_path + f'/{filepath}'
        with open(openfile, 'wb') as temp_file:
            for chunk in file.file:
                temp_file.write(chunk)
        return filepath
    except:
        msg = 'error'
        raise CustomException(err_desc=msg)


# ---------------------------------------- 服务器保存 ------------------------------------------------------------------


def save_to_server_storage_file(file, folder='', auth_file_type_list=None, auth_type=False, file_name=None):
    try:
        f_type = str(file.filename).split('.')[-1]
        f_nem = str(file.filename)[:-len(f_type) - 1]
        file_type = auth_file_type_list if auth_file_type_list else default_Type_list
        if auth_type and str(f_type).lower() not in file_type:
            msg = f'不支持{f_type}, 仅支持{",".join(file_type)}格式'
            raise CustomException(err_desc=msg)
        byte_data = file.file

        if str(f_type).lower() in image_list:
            content_type = "image/png"
        elif str(f_type).lower() in svg_list:
            content_type = "image/svg+xml"
        else:
            content_type = "application/octet-stream"

        if file_name:
            to_path = folder + '/' + file_name + '.' + f_type
        else:
            file_name = get_now_time_string()
            to_path = folder + '/' + file_name + '.' + f_type
        to_path = to_path.replace('\\', '/')
        go_upload_file_have_size(byte_data, size=file.size, bucket=settings.MINIO_BUCKET, path_name=to_path, content_type=content_type)
        return to_path
    except:
        print(traceback.format_exc())
        msg = 'save file error'
        raise CustomException(err_desc=msg)


def delete_to_server_storage_file(path):
    if path:
        ret = go_delete_file(bucket=settings.MINIO_BUCKET, path_name=path)
        return ret
    else:
        return None


def match_ipv4_address(route_string, proxy_url):
    pattern = r'(http://|https://)\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b:\b[0-9]{1,5}\b'
    # match = re.search(pattern, route_string)
    new_url = re.sub(pattern, proxy_url, route_string)
    return new_url


def get_to_server_storage_file(name):
    if name:
        # url = get_file_url(bucket=settings.MINIO_BUCKET, path_name=str(name))
        # # 走代理
        # return match_ipv4_address(url, settings.MINIO_PROXY)
        return settings.MINIO_PROXY + '/' + name
    else:
        return None


save_storage_file = save_to_server_storage_file
delete_storage_file = delete_to_server_storage_file
get_storage_file = get_to_server_storage_file
